import logging
import math
from typing import Optional, List

import requests
from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from config import SMARTSCREEN_PREFIX
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

smart_screen_router = APIRouter(prefix="/smartScreen", tags=["大屏接口"], dependencies=[Depends(oauth2_scheme)])


class QuerySearch(BaseModel):
    fsiteNo: str = Field(..., description="客户编号")


@smart_screen_router.get("/getTotalEleByFsiteNo", summary="")
def list_total_ele_by_fsite_no(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = "select sum(fuse_num) from S_TH_SMART_MONITER where fsite_no = :fsiteNo "
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()

    if sqlResult is not None and len(sqlResult) > 0:
        data = sqlResult[0][0]
        return BaseResponse.success(data=data)
    return BaseResponse.success()


@smart_screen_router.get("/getVoltageByFsiteNo", summary="")
def list_voltage_by_fsite_no(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = "select fpoint_flag qianYa,fnum1 guoYa,fnum2 guoZai from proc_rpt_electricwarring( :fsiteNo );"
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = {}
    if (len(sqlResult) > 0):
        for key in range(len(sqlResult)):
            qianYa = sqlResult[key][0]
            guoYa = sqlResult[key][1]
            guoZai = sqlResult[key][2]
            resultData = {"qianYa": qianYa, "guoYa": guoYa, "guoZai": guoZai}
    return BaseResponse.success(data=resultData)


@smart_screen_router.get("/getHuanBiByFsiteNo", summary="")
def list_huanbi_by_fsite_no(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = "select FDAY1 hbzr, FDAY3 hbsz, FDAY2 tbqn, FLEVEL2 sybl from proc_screen_smartrate(1, :fsiteNo );"
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = {}
    if (len(sqlResult) > 0):
        for key in range(len(sqlResult)):
            hbzr = sqlResult[key][0]
            hbsz = sqlResult[key][1]
            tbqn = sqlResult[key][2]
            sybl = sqlResult[key][3]
            resultData = {"hbzr": hbzr, "hbsz": hbsz, "tbqn": tbqn, "sybl": sybl}
    return BaseResponse.success(data=resultData)


@smart_screen_router.get("/getAverageVoltageByFsiteNo", summary="")
def list_average_voltage_by_fsiteno(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    paramers = {"fsiteNo": search.fsiteNo}
    try:
        response = requests.get(SMARTSCREEN_PREFIX + "/getAverageVoltageByFsiteNo", params=paramers)
        jsondata = response.json()
        if response.status_code == 200:
            code = jsondata["code"]
            data = jsondata["data"]
            msg = jsondata["msg"]
            return BaseResponse.success(data=data, message=msg)
        else:
            return BaseResponse.error(code=response.status_code, message="调用失败")
    except Exception as e:
        logging.error(">>>>> 网络连接redis失败")
        return BaseResponse.error(message=str(e))


@smart_screen_router.get("/getSchool24Ele", summary="")
def list_school_24ele(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = "select ftime fhour,fuse_num,fuse_num2 from PROC_SCREEN_SMARTTIME(4, :fsiteNo ) order by cast(ftime as integer);"
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = []
    if sqlResult is not None and len(sqlResult) > 0:
        for key in range(len(sqlResult)):
            fhour = sqlResult[key][0]
            fuseNum = sqlResult[key][1]
            fuseNum2 = sqlResult[key][2]
            item = {"fhour": fhour, "fuseNum": fuseNum, "fuseNum2": fuseNum2}
            resultData.append(item)
    commonResult = {"list": resultData}
    return BaseResponse.success(data=commonResult)


@smart_screen_router.get("/getSchoolEle", summary="")
def list_school_ele(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = "select fsite_no fpoint_no,fsite_name fpoint_name,fday1 fuse_num,fday2,fday3 fpoint_h,flevel2,flevel3 fpoint_w,flinkmac fpoint_l,flinkmark fpoint_d from PROC_SCREEN_SMARTTOT(4, :fsiteNo )  order by fsite_no "
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = []
    if sqlResult is not None and len(sqlResult) > 0:
        for key in range(len(sqlResult)):
            fpointNo = sqlResult[key][0]
            fpointName = sqlResult[key][1]
            fuseNum = sqlResult[key][2]
            fday2 = sqlResult[key][3]
            fpointH = sqlResult[key][4]
            flevel2 = sqlResult[key][5]
            fpointW = sqlResult[key][6]
            fpointL = sqlResult[key][7]
            fpointD = sqlResult[key][8]
            item = {"fpointNo": fpointNo, "fpointName": fpointName, "fuseNum": fuseNum, "fday2": fday2,
                    "fpointH": fpointH, "flevel2": flevel2, "fpointW": fpointW, "fpointL": fpointL, "fpointD": fpointD}
            resultData.append(item)

    commonResult = {"list": resultData}
    return BaseResponse.success(data=commonResult)


class EquipmentTypeElementSearch(BaseModel):
    """设备类型元素查询请求参数"""
    fsiteNo: str = Field(..., description="站点编号")
    filterZero: str = Field("1", description="是否过滤零值，1表示过滤，0表示不过滤，默认1")


@smart_screen_router.get("/getEqtTypeEleByFsiteNo", summary="")
def list_equ_type_ele_by_fsiteno(search: EquipmentTypeElementSearch = Query(), db: Session = Depends(get_db)):
    sql = "select fsite_no,fsite_name,fday1 electric,FPOINT_NO as frate from PROC_SCREEN_SMARTTOT(7, :fsiteNo ) where fsite_no is not null "
    if search.filterZero == "1":
        sql = sql + " and fday1 <> 0;"
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = []
    if sqlResult is not None and len(sqlResult) > 0:
        for key in range(len(sqlResult)):
            fsiteNo = sqlResult[key][0]
            fsiteName = sqlResult[key][1]
            electric = sqlResult[key][2]
            frate = sqlResult[key][3]
            item = {"fsiteNo": fsiteNo, "fsiteName": fsiteName, "electric": electric, "frate": frate}
            resultData.append(item)
    commonResult = {"list": resultData}
    return BaseResponse.success(data=commonResult)


@smart_screen_router.get("/getClassroom24Ele", summary="")
def list_classroom_24ele(search: QuerySearch = Query(), db: Session = Depends(get_db)):
    sql = " select ftime fhour, fuse_num, fuse_num2 from PROC_SCREEN_SMARTTIME(6, :fsiteNo )  order by cast(ftime as integer);"
    sqlResult = db.execute(text(sql), {
        "fsiteNo": search.fsiteNo
    }).fetchall()
    resultData = []
    if sqlResult is not None and len(sqlResult) > 0:
        for key in range(len(sqlResult)):
            fhour = sqlResult[key][0]
            fuseNum = sqlResult[key][1]
            fuseNum2 = sqlResult[key][2]
            item = {"fhour": fhour, "fuseNum": fuseNum, "fuseNum2": fuseNum2}
            resultData.append(item)
    result = {"list": resultData}

    return BaseResponse.success(data=result)
